<template>
  <div class="task-detail-view">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>地铁隧道巡线车智能巡检系统</el-breadcrumb-item>
      <el-breadcrumb-item>
        <router-link to="/task">任务列表</router-link>
      </el-breadcrumb-item>
      <el-breadcrumb-item>任务详情</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 顶部右侧数据库开关 -->
    <el-switch
        v-model="settingStore.useDb"
        class="db-switcher"
        active-text="读取数据库"
        inactive-text="实时模式"
        @change="handleDbSwitch"
    />
    

    <el-row :gutter="20" class="main-area">
      <el-col :span="16" class="image-area-wrapper">
        <div class="image-area">
          <el-image
              v-if="currentFlawImage"
              :src="currentFlawImage"
              :preview-src-list="previewList"
              fit="contain"
              class="flaw-image"
          >
            <template #error>
              <div class="image-placeholder">暂无图片</div>
            </template>
          </el-image>
          <div v-else class="image-placeholder">暂无故障图像</div>
        </div>

        <!-- 进度条 -->
        <div class="scale-bar-area">
          <div class="scale-bar-wrapper">
            <span class="scale-bar-text start">0m</span>
            <span class="scale-bar-text end">{{ taskInfo?.taskTrip }}m</span>
            <div class="scale-bar">
              <div class="scale-bar-progress" style="width: 100%"></div>
            </div>
            <template v-for="flaw in flaws" :key="flaw.id">
              <div
                  class="scale-bar-flaw"
                  :class="flawClass(flaw)"
                  :style="{ left: calcLeft(flaw) }"
                  :title="flaw.flawName"
                  @click="selectFlaw(flaw)"
              >📍</div>
            </template>
          </div>
        </div>
      </el-col>

      <!-- 右侧信息栏 -->
      <el-col :span="8" class="sidebar" v-loading="loading">
        <el-card shadow="never" class="mb-10">
          <template #header>任务信息</template>
          <el-descriptions column="1" border>
            <el-descriptions-item label="巡视任务编号">{{ taskInfo?.taskCode }}</el-descriptions-item>
            <el-descriptions-item label="巡视开始时间">{{ taskInfo?.execTime }}</el-descriptions-item>
            <el-descriptions-item label="巡视结束时间">{{ taskInfo?.endTime }}</el-descriptions-item>
            <el-descriptions-item label="巡视行驶距离">{{ taskInfo?.taskTrip }} 米</el-descriptions-item>
            <el-descriptions-item label="故障总计">{{ flaws.length }}</el-descriptions-item>
            <el-descriptions-item label="已确定故障"><span class="confirmed-flaw">{{ confirmedCount }}</span></el-descriptions-item>
            <el-descriptions-item label="疑似故障"><span class="unconfirmed-flaw">{{ unconfirmedCount }}</span></el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="never">
          <template #header>故障历史</template>
          <el-table :data="flaws" stripe size="small" @row-click="selectFlaw">
            <el-table-column prop="flawName" label="故障名称">
              <template #default="{ row }">
                <el-link type="primary">{{ row.flawName }}</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="flawType" label="故障类型" width="90" />
            <el-table-column prop="flawDistance" label="位置(m)" width="80" />
            <el-table-column prop="confirmed" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.confirmed ? 'danger' : row.confirmed === false ? 'info' : 'warning'">
                  {{ row.confirmed ? '已确认' : row.confirmed === false ? '误报' : '待确认' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 故障详情模态框 -->
    <el-dialog v-model="detailVisible" title="故障详情" width="60%">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-image
              :src="'http://192.168.2.57/prod-api/file' + selectedFlaw?.flawImageUrl"
              :preview-src-list="selectedFlaw ? ['http://192.168.2.57/prod-api/file' + selectedFlaw.flawImageUrl] : []"
              fit="contain"
              style="width: 100%; height: 450px"
          >
            <template #error>
              <div class="image-placeholder">暂无图片</div>
            </template>
          </el-image>
        </el-col>
        <el-col :span="8">
          <el-descriptions column="1" border>
            <el-descriptions-item label="故障名称">{{ selectedFlaw?.flawName }}</el-descriptions-item>
            <el-descriptions-item label="故障类型">{{ selectedFlaw?.flawType }}</el-descriptions-item>
            <el-descriptions-item label="故障描述">{{ selectedFlaw?.flawDesc }}</el-descriptions-item>
            <el-descriptions-item label="故障位置">{{ selectedFlaw?.flawDistance }} m</el-descriptions-item>
            <el-descriptions-item label="确认状态">
              <el-radio-group v-model="confirmValue">
                <el-radio :label="true">属实</el-radio>
                <el-radio :label="false">误报</el-radio>
              </el-radio-group>
            </el-descriptions-item>
            <el-descriptions-item label="补充说明">
              <el-input v-model="remark" type="textarea" rows="4" />
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      <template #footer>
        <el-button @click="detailVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveFlaw" :loading="saving">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
  getFlaw,
  getTask,
  listFlaw,
  liveInfo,
  updateFlaw,
  upsertTaskDb,
  upsertFlawDb
} from '@/axios/api';
import type { AgvTask, AgvFlaw } from '@/axios/types';
import { ElMessage } from 'element-plus';
import { useSetting } from '@/stores/setting';

const route = useRoute();
const router = useRouter();
const taskId = Number(route.params.id);
const loading = ref(false);

const taskInfo = ref<AgvTask>();
const flaws = ref<AgvFlaw[]>([]);
const currentFlawImage = ref<string>('');

const previewList = computed(() => (currentFlawImage.value ? [currentFlawImage.value] : []));

const confirmedCount = computed(() => flaws.value.filter(f => f.confirmed === true).length);
const unconfirmedCount = computed(() => flaws.value.filter(f => f.confirmed === undefined || f.confirmed === null).length);

const settingStore = useSetting();

const fetchData = async () => {
  loading.value = true;
  try {
    const [taskRes, flawRes] = await Promise.all([
      getTask(taskId),
      liveInfo(taskId)
    ]);

    taskInfo.value = taskRes.data;
    flaws.value = flawRes.data || [];
    console.log(flawRes);
    if (flaws.value.length) {
      currentFlawImage.value = "http://192.168.2.57/prod-api/file" + flaws.value[0].flawImageUrl || '';
    }

    // 同步到本地数据库（实时模式）
    if (!settingStore.useDb) {
      if (taskInfo.value) {
        upsertTaskDb(taskInfo.value).catch(err => console.error('同步任务到DB失败', err));
      }
      if (Array.isArray(flaws.value)) {
        const promises = flaws.value.map(item => upsertFlawDb(item));
        Promise.all(promises).catch(err => console.error('同步缺陷到DB失败', err));
      }
    }
  } finally {
    loading.value = false;
  }
};

onMounted(fetchData);

const calcLeft = (flaw: AgvFlaw) => {
  if (!taskInfo.value?.taskTrip) return '0%';
  const percent = (Number(flaw.flawDistance || 0) / Number(taskInfo.value.taskTrip)) * 100;
  return `${percent}%`;
};

const flawClass = (flaw: AgvFlaw) => {
  if (flaw.confirmed === true) return 'confirmed';
  if (flaw.confirmed === false) return 'false';
  return 'unconfirmed';
};

const selectFlaw = (flaw: AgvFlaw) => {
  currentFlawImage.value = "http://192.168.2.57/prod-api/file" + flaw.flawImageUrl || '';
  selectedFlaw.value = flaw;
  confirmValue.value = flaw.confirmed ?? true;
  remark.value = flaw.remark || '';
  detailVisible.value = true;
  console.log(flaw);
};

const detailVisible = ref(false);
const selectedFlaw = ref<AgvFlaw>();
const confirmValue = ref<boolean | null>(true);
const remark = ref('');
const saving = ref(false);

const saveFlaw = async () => {
  if (!selectedFlaw.value?.id) return;
  saving.value = true;
  try {
    await updateFlaw({
      ...selectedFlaw.value,
      confirmed: confirmValue.value,
      remark: remark.value
    });
    ElMessage.success('保存成功');
    detailVisible.value = false;
    await fetchData();
  } finally {
    saving.value = false;
  }
};

const goBack = () => router.back();

const handleDbSwitch = () => {
  fetchData();
};
</script>

<style scoped>
.main-area {
  margin-top: 20px;
}

.task-detail-view {
  padding: 20px;
  position: relative;
}
.back-btn {
  position: absolute;
  right: 120px; /* 给 Switcher 让位 */
  top: 18px;
}
.image-area-wrapper {
  display: flex;
  flex-direction: column;
}
.image-area {

  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  height: 80vh;
}
.image-placeholder {
  color: #bbb;
  font-size: 16px;
}
.scale-bar-area {
  background: #fafafa;
  border-top: 1px solid #eee;
  padding: 20px;
}
.scale-bar-wrapper {
  position: relative;
  height: 40px;
}
.scale-bar {
  width: 100%;
  height: 8px;
  background: #e4e7ed;
  border-radius: 4px;
  position: relative;
  margin: 16px 0;
}
.scale-bar-progress {
  height: 100%;
  background: #409eff;
  border-radius: 4px;
}
.scale-bar-text {
  position: absolute;
  font-size: 12px;
  color: #666;
}
.scale-bar-text.start {
  left: 0;
  top: -15px;
}
.scale-bar-text.end {
  right: 0;
  top: -15px;
}
.scale-bar-flaw {
  position: absolute;
  top: 4px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  cursor: pointer;
  transform: translateX(-50%);
}
.scale-bar-flaw.confirmed {
  background: #f56c6c;
  color: white;
}
.scale-bar-flaw.unconfirmed {
  background: #e6a23c;
  color: white;
}
.scale-bar-flaw.false {
  background: #909399;
  color: white;
}
.sidebar .mb-10 {
  margin-bottom: 10px;
}
.confirmed-flaw { color: #f56c6c; font-weight: bold; }
.unconfirmed-flaw { color: #e6a23c; font-weight: bold; }
.db-switcher {
  position: absolute;
  top: 18px;
  right: 20px;
}
</style>